﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
using System.Xml.Linq;
using System.Xml;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Threading;

namespace Study.Ajax
{
    /// <summary>
    /// WeChat 的摘要说明
    /// </summary>
    public class WeChat : IHttpHandler
    {
        private static List<Friend> list = new List<Friend>();

        private static string uuid="";
        private static string skey = "";
        private static string sid = "";
        private static string uin = "";
        private static string pass_ticket = "";
        private static string me = "";
        private static string syncKey="";
        private static string deviceId = "e243213377963345";

        private static string redirect_uri = "";



        public void ProcessRequest(HttpContext context)
        {
            string opt = context.Request["opt"].ToString();
            switch (opt)
            { 
                case "getQRcode":GetQRCode(context);
                    break;
                case "get_redirect_uri": Get_Redirect_Url(context);
                    break;
            }                       
        }

        private static void Get_Redirect_Url(HttpContext context)
        {
            list.Clear();
            string get_redirect_uri = "https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?uuid=" + uuid + "&tip=1&_=1377482045264";
            string responseStr = "";
            WebRequest request = null;
            WebResponse response = null;
            Stream ReceiveStream = null;
            while (responseStr.IndexOf("redirect_uri=") == -1)
            {
                request = WebRequest.Create(get_redirect_uri);
                response = request.GetResponse();
                ReceiveStream = response.GetResponseStream();

                if (ReceiveStream != null)
                {
                    StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
                response.Close();
            }

            redirect_uri = responseStr.Substring(responseStr.IndexOf("redirect_uri=") + 14, responseStr.Length - responseStr.IndexOf("redirect_uri=") - 16);
            string ticket = responseStr.Substring(responseStr.IndexOf("ticket=") + 7, responseStr.IndexOf("&uuid") - responseStr.IndexOf("ticket=")-7);
            string scan = responseStr.Substring(responseStr.IndexOf("scan=") + 5, responseStr.Length-responseStr.IndexOf("scan=") - 7);

            string login_url = "https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxnewloginpage?ticket="+ticket+"&uuid="+uuid+"&lang=zh_CN&scan="+scan+"&fun=new&version=v2&lang=zh_CN";

            request = WebRequest.Create(login_url);
            response = request.GetResponse();
            ReceiveStream = response.GetResponseStream();

            if (ReceiveStream != null)
            {
                StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
                responseStr = reader.ReadToEnd();
                reader.Close();
            }
            response.Close();

            XmlDocument xml = new XmlDocument();
            xml.LoadXml(responseStr);
            XmlNode root = xml.SelectSingleNode("//error");
            skey = root.SelectSingleNode("skey").InnerText;
            sid = root.SelectSingleNode("wxsid").InnerText;
            uin = root.SelectSingleNode("wxuin").InnerText;
            pass_ticket = root.SelectSingleNode("pass_ticket").InnerText;

            //---微信初始化---------
            #region 微信初始化
            string wx_init_info = "https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxinit?r=-1766680381&lang=zh_CN&pass_ticket="+pass_ticket;
            request = WebRequest.Create(wx_init_info);
            string JSONData = "{\"BaseRequest\":{\"Uin\":\"" + uin + "\",\"Sid\":\"" + sid + "\",\"Skey\":\"" + skey + "\",\"DeviceID\":\""+deviceId+"\"}}";
            byte[] bytes = Encoding.UTF8.GetBytes(JSONData);
            request.Method = "POST";
            request.ContentType = "text/xml";
            request.ContentLength = bytes.Length;
            request.GetRequestStream().Write(bytes, 0, bytes.Length);
            response = request.GetResponse();
            ReceiveStream = response.GetResponseStream();
            if (ReceiveStream != null)
            {
                StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
                responseStr = reader.ReadToEnd();
                reader.Close();
            }
            JObject obj = (JObject)JsonConvert.DeserializeObject(responseStr);
            obj = (JObject)JsonConvert.DeserializeObject(obj["User"].ToString());
            me = obj["UserName"].ToString();

            obj = (JObject)JsonConvert.DeserializeObject(responseStr);
            syncKey = obj["SyncKey"].ToString();
            obj=(JObject)JsonConvert.DeserializeObject(syncKey);
            string list2 = obj["List"].ToString();
            JArray array2 = JArray.Parse(list2);
            string syncKey2 = "";
            for (int i = 0; i < array2.Count; i++)
            {
                syncKey2 = syncKey2 + array2[i]["Key"] + "_" + array2[i]["Val"]+"|";
            }
            syncKey2 = syncKey2.Substring(0, syncKey2.Length-1);
            response.Close();
            #endregion 微信初始化

            string notify_url = "https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxstatusnotify?lang=zh_CN&pass_ticket="+pass_ticket;
            
            

            //request = WebRequest.Create(notify_url);
            //request.Method = "POST";
            //request.ContentType = "text/xml";
            
            //ReceiveStream = response.GetResponseStream();
            //if (ReceiveStream != null)
            //{
            //    StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
            //    responseStr = reader.ReadToEnd();
            //    reader.Close();
            //}
            //response.Close();

            //获取好友(包括群)列表
            #region 获取好友(包括群)列表             
            string get_friends_list_url = "https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxgetcontact?lang=zh_CN&pass_ticket="+pass_ticket+"&r=1453525907497&seq=0&skey="+skey;
            request = WebRequest.Create(get_friends_list_url);
            request.Method = "POST";
            request.ContentType = "text/xml";
            request.ContentLength = bytes.Length;
            request.GetRequestStream().Write(bytes, 0, bytes.Length);
            response = request.GetResponse();
            ReceiveStream = response.GetResponseStream();

            if (ReceiveStream != null)
            {
                StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
                responseStr = reader.ReadToEnd();
                reader.Close();
            }
            JObject jo = (JObject)JsonConvert.DeserializeObject(responseStr);
            string s =jo["MemberList"].ToString();
            JArray array = JArray.Parse(s);
            for (int i = 0; i < array.Count; i++)
            {
                JObject j = JObject.Parse(array[i].ToString());
                Friend friend = new Friend();
                friend.Uin =Convert.ToInt32( j["Uin"].ConvertObjToStr());
                friend.UserName = j["UserName"].ConvertObjToStr();
                friend.NickName = j["NickName"].ConvertObjToStr();
                friend.HeadImgUrl = j["Uin"].ConvertObjToStr();
                friend.ContactFlag = Convert.ToInt32(j["Uin"].ConvertObjToStr());
                friend.MemberCount = Convert.ToInt32(j["Uin"].ConvertObjToStr());
                //friend.MemberList = j["Uin"].ConvertObjToStr().ToArray<string>();
                friend.RemarkName = j["RemarkName"].ConvertObjToStr();
                friend.HideInputBarFlag = Convert.ToInt32(j["Uin"].ConvertObjToStr());
                friend.Sex = Convert.ToInt32(j["Uin"].ConvertObjToStr());
                friend.Signature = j["Uin"].ConvertObjToStr();
                friend.VerifyFlag = Convert.ToInt32(j["Uin"].ConvertObjToStr());
                friend.OwnerUin = Convert.ToInt32(j["Uin"].ConvertObjToStr());
                friend.PYInitial = j["Uin"].ConvertObjToStr();
                friend.PYQuanPin = j["Uin"].ConvertObjToStr();
                friend.RemarkPYInitial = j["Uin"].ConvertObjToStr();
                friend.RemarkPYQuanPin = j["Uin"].ConvertObjToStr();
                friend.StarFriend = Convert.ToInt32(j["Uin"].ConvertObjToStr());
                friend.AppAccountFlag = Convert.ToInt32(j["Uin"].ConvertObjToStr());
                friend.Statues = Convert.ToInt32(j["Uin"].ConvertObjToStr());
                friend.AttrStatus = Convert.ToInt32(j["Uin"].ConvertObjToStr());
                friend.Province = j["Uin"].ConvertObjToStr();
                friend.City = j["Uin"].ConvertObjToStr();
                friend.Alias = j["Uin"].ConvertObjToStr();
                friend.SnsFlag = Convert.ToInt32(j["Uin"].ConvertObjToStr());
                friend.UniFriend = Convert.ToInt32(j["Uin"].ConvertObjToStr());
                friend.DisplayName = j["Uin"].ConvertObjToStr();
                friend.AttrStatus = Convert.ToInt32(j["Uin"].ConvertObjToStr());
                friend.ChatRoomId = Convert.ToInt32(j["Uin"].ConvertObjToStr());
                friend.KeyWord = j["Uin"].ConvertObjToStr();
                friend.EncryChatRoomId = j["Uin"].ConvertObjToStr();
                friend.IsOwner = Convert.ToInt32(j["Uin"].ConvertObjToStr());
                list.Add(friend);
            } 
            response.Close();
            #endregion 获取好友(包括群)列表

            string uu = "https://webpush.weixin.qq.com/cgi-bin/mmwebwx-bin/synccheck?callback=jQuery18309326978388708085_1377482079946&r=1377482079876&sid="+sid+"&uin="+uin+"&deviceid="+deviceId+"&synckey="+syncKey2+"&_=1377482079876";
            

            StringBuilder sb_notify = new StringBuilder();
            sb_notify.Append("\"BaseRequest\":{");
            sb_notify.Append("\"ClientMsgId\":1453686440414,");
            sb_notify.Append("\"Code\":3,");
            sb_notify.Append("\"FromUserName\":\"" + me + "\",");
            sb_notify.Append("\"ToUserName\":\"" + me + "\"}");
            string sss = sb_notify.ToString();
            byte[] notify_byte = Encoding.UTF8.GetBytes(sb_notify.ToString());
            
            request = WebRequest.Create(uu);
            request.Method = "POST";
            request.ContentType = "text/xml";
            request.ContentLength = notify_byte.Length;
            request.GetRequestStream().Write(notify_byte, 0, notify_byte.Length);
            response = request.GetResponse();
            ReceiveStream = response.GetResponseStream();
            if (ReceiveStream != null)
            {
                StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
                responseStr = reader.ReadToEnd();
                reader.Close();
            }
            response.Close();


            //---------获取群消息列表----------
            //string get_group_list_url = "https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxbatchgetcontact?type=ex&r=1453686440414&lang=zh_CN&pass_ticket="+pass_ticket;
            //request = WebRequest.Create(get_group_list_url);
            //request.Method = "POST";
            //request.ContentType = "text/xml";
            //request.ContentLength = bytes.Length;
            //request.GetRequestStream().Write(bytes, 0, bytes.Length);
            //response = request.GetResponse();
            //ReceiveStream = response.GetResponseStream();
            //if (ReceiveStream != null)
            //{
            //    StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
            //    responseStr = reader.ReadToEnd();
            //    reader.Close();
            //}
            //response.Close();
            //---------获取群消息列表----------

            string get_new_msg_url = "https://webpush.weixin.qq.com/cgi-bin/mmwebwx-bin/webwxsync?sid=" + sid + "&r=1393208447375";
            string url = "https://webpush.weixin.qq.com/cgi-bin/mmwebwx-bin/synccheck?callback=jQuery18306073923335455973_1393208247730&r=1393209241862&sid="+sid+"&uin="+uin+ "&deviceid="+deviceId+"&synckey=1_620943725%7C2_620943769%7C3_620943770%7C11_620942796%7C201_1393208420%7C202_1393209127%7C1000_1393203219&_=1393209241865";

            while (!true)
            {
                request = WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "text/xml";
                response = request.GetResponse();
                ReceiveStream = response.GetResponseStream();

                if (ReceiveStream != null)
                {
                    StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
                response.Close();
            }



            StringBuilder sb_new_msg = new StringBuilder();
            sb_new_msg.Append("{\"BaseRequest\":{");
            sb_new_msg.Append("\"Uin\":"+uin+",");
            sb_new_msg.Append("\"Sid\":\""+sid+"\"},");
            sb_new_msg.Append("\"SyncKey\":"+syncKey);
            sb_new_msg.Append(",\"rr\":1393208447374}");
            string s1 = sb_new_msg.ToString();
            byte[] ps_new_msg = Encoding.UTF8.GetBytes(sb_new_msg.ToString());

            while (!true)
            {
                request = WebRequest.Create(get_new_msg_url);
                request.Method = "POST";
                request.ContentType = "text/xml";
                request.ContentLength = ps_new_msg.Length;
                request.GetRequestStream().Write(ps_new_msg, 0, ps_new_msg.Length);
                response = request.GetResponse();
                ReceiveStream = response.GetResponseStream();

                if (ReceiveStream != null)
                {
                    StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
                response.Close();
            }

            //网页端与手机端状态同步心跳
            string webAndMobile_sync_url = "https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxstatusnotify?r=1397443950116&skey=" + skey;
            StringBuilder sb_sync = new StringBuilder();
            sb_sync.Append("{\"BaseRequest\":{");
            sb_sync.Append("\"Uin\":" + uin + ",");
            sb_sync.Append("\"Sid\":\"" + sid + "\",");
            sb_sync.Append("\"Skey\":\"" + skey + "\",");
            sb_sync.Append("\"DeviceID\":\"e677104163849055\"},");
            sb_sync.Append("\"Code\":3,");
            sb_sync.Append("\"FromUserName\":\"" + me + "\",");
            sb_sync.Append("\"ToUserName\":\"" + me + "\",");
            sb_sync.Append("\"ClientMsgId\":1499310509652}");
            byte[] sync_bytes = Encoding.UTF8.GetBytes(sb_sync.ToString());

            request = WebRequest.Create(webAndMobile_sync_url);
            request.Method = "POST";
            request.ContentType = "text/xml";
            request.ContentLength = sync_bytes.Length;
            request.GetRequestStream().Write(sync_bytes, 0, sync_bytes.Length);
            response = request.GetResponse();
            ReceiveStream = response.GetResponseStream();

            if (ReceiveStream != null)
            {
                StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
                responseStr = reader.ReadToEnd();
                reader.Close();
            }
            response.Close();


            //发送消息
                        
            string send_msg_url = "https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxsendmsg?pass_ticket=" + pass_ticket;

            for (int i=1;i<21;i++)
            {
                Thread.Sleep(1000);
                request = WebRequest.Create(send_msg_url);
                request.Method = "POST";
                request.ContentType = "text/xml";
                string user = list.Where(p => p.RemarkName == "D李总").FirstOrDefault().UserName;
                byte[] msg_bytes = GetSendMsgPs(user, "测试用，不用回复,第"+i+"条");
                request.ContentLength = msg_bytes.Length;
                request.GetRequestStream().Write(msg_bytes, 0, msg_bytes.Length);
                response = request.GetResponse();
                ReceiveStream = response.GetResponseStream();

                if (ReceiveStream != null)
                {
                    StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
                response.Close();
            }
            //发送消息

            



            //--------------接收消息---------------------------------------
            string get_msg_url = "https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxsync?sid="+sid+"&skey="+skey+"&pass_ticket="+pass_ticket;
            while (!true)
            {
                request = WebRequest.Create(get_msg_url);
                request.Method = "POST";
                request.ContentType = "text/xml";
                request.ContentLength = bytes.Length;
                request.GetRequestStream().Write(bytes, 0, bytes.Length);
                response = request.GetResponse();
                ReceiveStream = response.GetResponseStream();

                if (ReceiveStream != null)
                {
                    StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
                response.Close();
            }
            //--------------接收消息---------------------------------------

            
            

        }

        /// <summary>
        /// 拼装发送消息所需的参数
        /// </summary>
        /// <param name="sid"></param>
        /// <param name="skey"></param>
        /// <param name="uin"></param>
        /// <param name="receiver"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        private static byte[] GetSendMsgPs(string receiver,string msg)
        {
            StringBuilder ps = new StringBuilder();
            ps.Append("{\"BaseRequest\":");
            ps.Append("{\"DeviceID\" : \"e243213377963345\",");
            ps.Append("\"Sid\" : \"" + sid + "\",");
            ps.Append("\"Skey\" : \"" + skey + "\",");
            ps.Append("\"Uin\" : " + uin + "},");
            ps.Append("\"Msg\" : {");
            ps.Append("\"ClientMsgId\" : \"14993105981190909\",");
            ps.Append("\"Content\" : \"" + msg + "\",");
            ps.Append("\"FromUserName\" : \"" + me + "\",");
            ps.Append("\"LocalID\" :\"14993105981190909\",");
            ps.Append("\"ToUserName\" : \"" + receiver + "\",");
            ps.Append("\"Type\" : 1},");
            ps.Append("\"Scene\":0}");
            string s = ps.ToString();
            byte[] msg_bytes = Encoding.UTF8.GetBytes(ps.ToString());
            return msg_bytes;
        }

        private static void GetQRCode(HttpContext context)
        {
            string qrCode = "";
            string get_uuid = "https://login.weixin.qq.com/jslogin?appid=wx782c26e4c19acffb&redirect_uri=https%3A%2F%2Fwx.qq.com%2Fcgi-bin%2Fmmwebwx-bin%2Fwebwxnewloginpage&fun=new&lang=zh_CN&_=1453465626377";
            WebRequest myWebRequest = WebRequest.Create(get_uuid);
            WebResponse myWebResponse = myWebRequest.GetResponse();
            Stream ReceiveStream = myWebResponse.GetResponseStream();
            string responseStr = "";
            if (ReceiveStream != null)
            {
                StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
                responseStr = reader.ReadToEnd();
                reader.Close();
            }
            myWebResponse.Close();
            uuid = responseStr.Substring(responseStr.IndexOf("uuid = ") + 8, responseStr.Length - responseStr.IndexOf("uuid = ") - 10);
            qrCode = "https://login.weixin.qq.com/qrcode/" + uuid;
            context.Response.Write(qrCode);
        }

        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        public static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

    [Serializable]
    public class Friend
    {
        public int Uin { get; set; }
        public string UserName { get; set; }
        public string NickName { get; set; }
        public string HeadImgUrl { get; set; }
        public int ContactFlag { get; set; }
        public int MemberCount { get; set; }
        public Array[] MemberList { get; set; }
        public string RemarkName { get; set; }
        public int HideInputBarFlag { get; set; }
        public int Sex { get; set; }
        public string Signature { get; set; }
        public int VerifyFlag { get; set; }
        public int OwnerUin { get; set; }
        public string PYInitial { get; set; }
        public string PYQuanPin { get; set; }
        public string RemarkPYInitial { get; set; }
        public string RemarkPYQuanPin { get; set; }
        public int StarFriend { get; set; }
        public int AppAccountFlag { get; set; }
        public int Statues { get; set; }
        public int AttrStatus { get; set; }
        public string Province { get; set; }
        public string City { get; set; }
        public string Alias { get; set; }
        public int SnsFlag { get; set; }
        public int UniFriend { get; set; }
        public string DisplayName { get; set; }
        public int ChatRoomId { get; set; }
        public string KeyWord { get; set; }
        public string EncryChatRoomId { get; set; }
        public int IsOwner { get; set; }
    }
}